import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage, connect, ConnectProps } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';

import ImportForm from './components/ImportForm';
import UpdateForm from './components/UpdateForm';
import InfoForm from './components/InfoForm';
import ViewForm from './components/ViewForm';

import type { TableListItem } from './data';
import { queryData, updateData, saveData, removeData, createGencode } from './service';



/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在配置');
  try {
    await updateData(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleRemoveOne = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    let params = [selectedRow.id]
    await removeData({
      ids: params,
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    console.log(error)
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const gencode = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在生成');
  if (!selectedRow) return true;
  try {
    await createGencode(selectedRow.id);
    hide();
    message.success('生成成功，即将刷新');
    return true;
  } catch (error) {
    console.log(error)
    hide();
    message.error('生成失败，请重试');
    return false;
  }
};

export type GlobalTableProps = {
  currentUser?: CurrentUser;
} & Partial<ConnectProps>;

const TableList: React.FC<GlobalTableProps> = (props) => {
  /** 导入窗口的弹窗 */
  const [importModalVisible, handleImportModalVisible] = useState<boolean>(false);
  /** 更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  /** 详情窗口的弹窗 */
  const [infoModalVisible, handleInfoModalVisible] = useState<boolean>(false);
  /** 预览窗口的弹窗 */
  const [viewModalVisible, handleViewModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  /** 国际化配置 */
  const intl = useIntl();
  const { currentUser } = props;

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '表名称',
      dataIndex: 'table_name',
      tip: '表名称',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '表描述',
      dataIndex: 'table_comment',
      valueType: 'textarea',
    },
    {
      title: '模板类型',
      dataIndex: 'temp_type',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '单表',
        },
        1: {
          text: '树表',
        },
      },
    },
    {
      title: '生成包路径',
      dataIndex: 'pack_path',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '模块名称',
      dataIndex: 'mod_name',
      valueType: 'textarea',
    },
    {
      title: '业务名称',
      dataIndex: 'bus_name',
      valueType: 'textarea',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record) => [
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('gencode:viewCode') ? 'block' : 'none' }}
          onClick={() => {
            handleViewModalVisible(true);
            setCurrentRow(record);
          }}>
          预览
        </Button>,
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('gencode:gencode') ? 'block' : 'none' }}
          onClick={() => {
            gencode(record);
          }}>
          生成
        </Button>,
        <Button size='small' key="config"
          style={{ display: currentUser?.authButton.includes('gencode:info') ? 'block' : 'none' }}
          onClick={() => {
            handleInfoModalVisible(true);
            setCurrentRow(record);
          }}>
          详情
        </Button>,
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('gencode:edit') ? 'block' : 'none' }}
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}>
          编辑
        </Button>,
        <Button type="primary" size='small' danger
          style={{ display: currentUser?.authButton.includes('gencode:del') ? 'block' : 'none' }}
          onClick={async () => {
            Modal.confirm({
              title: '删除任务',
              content: '确定删除该任务吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                const success = handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}>
          删除
        </Button>,

      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '查询表格',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            style={{ display: currentUser?.authButton.includes('gencode:import') ? 'block' : 'none' }}
            onClick={() => {
              handleImportModalVisible(true);
            }}
          >
            <UploadOutlined /> 导入
          </Button>,
        ]}
        request={
          (params, sorter, filter) => queryData(params).then(res => {
            const result = {
              data: res.data.rows,
              total: res.data.total,
              success: true
            }
            return result
          })
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      // toolBarRender={false}
      // search={false}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            style={{ display: currentUser?.authButton.includes('gencode:del') ? 'block' : 'none' }}
            onClick={async () => {
              Modal.confirm({
                title: '删除任务',
                content: '确定删除该任务吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const success = handleRemove(selectedRowsState);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
          {/* <Button type="primary">
            <FormattedMessage id="pages.searchTable.batchApproval" defaultMessage="批量审批" />
          </Button> */}
        </FooterToolbar>
      )}
      <ImportForm
        onSubmit={async (value: any) => {
          const success = await saveData({ table_names: value.join(",") });
          // const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleImportModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleImportModalVisible(false);
          setCurrentRow(undefined);
        }}
        importModalVisible={importModalVisible}
        values={currentRow || {}}
      />
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate({ ...value, id: currentRow?.id });
          // const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <InfoForm
        onSubmit={async (value) => {
          handleInfoModalVisible(false);
          setCurrentRow(undefined);
        }}
        onCancel={() => {
          handleInfoModalVisible(false);
          setCurrentRow(undefined);
        }}
        infoModalVisible={infoModalVisible}
        values={currentRow || {}}
      />
      <ViewForm
        onSubmit={async (value) => {
          handleViewModalVisible(false);
          setCurrentRow(undefined);
        }}
        onCancel={() => {
          handleViewModalVisible(false);
          setCurrentRow(undefined);
        }}
        viewModalVisible={viewModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.table_name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.table_comment}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

// export default TableList;
export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);